// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

// 自定义ts类型必须要给ccclass传入name
@ccclass('CowSkin')
class CowSkin {
    @property([cc.SpriteFrame])
    cows: cc.SpriteFrame[] = []; // 奔跑动画图集

    @property()
    cowDifficulty: number = 100; // 牛儿难度

    @property()
    cowPrice: number = 1; // 牛儿的价格
}

@ccclass
export default class CowRun extends cc.Component {
    
    // 皮肤
    @property(CowSkin)
    cowSets: CowSkin[] = []

    intervalTime: number = 0; // 记录时间

    cowSprite: cc.Sprite = null; // 精灵组件

    cowType: number = 0; // 牛儿类型

    currentSkin: CowSkin = null; // 当前皮肤

    animationsNode: cc.AnimationState = null;

    onLoad () {
        this.cowSprite = this.node.getComponent(cc.Sprite) // 获取精灵组件
        this.onChangeType()

        // this.animationsNode = this.node.getComponent(cc.Animation).play();
    }

    start () {
    }

    update (dt) {
        this.intervalTime += dt; // 时间不停地增加
        let index: number = Math.floor(this.intervalTime / 0.2); // 每隔0.2秒更换一次皮肤 0.2/0.2=1，0.4/0.2=2

        index %= 3; // 最大为3
        // cc.log(index, 'index')

        this.currentSkin = this.cowSets[this.cowType];
        const cowset: cc.SpriteFrame = this.currentSkin.cows[index];

        this.cowSprite.spriteFrame = cowset;
    }

    onRunHandler(){
        this.animationsNode = this.node.getComponent(cc.Animation).play();
        const btn = cc.find('Canvas/startBtn');
        btn.removeFromParent()
        btn.destroy()
    }

    // 切换皮肤--
    onChangeType(){
        this.cowType = Math.floor( Math.random() * 3 )
        // console.log('onChangeType')
    }

    // 重新播放,刷新皮肤
    rePlayRun(){
        this.animationsNode = this.node.getComponent(cc.Animation).play();
        this.onChangeType()
    }

    // 更新速度
    changeSpeed(speed: number){
        this.animationsNode.speed += speed * 0.02
    }
}
